package com.ruoyi.product.utils;


import com.ruoyi.product.tree.DataTree;
import com.ruoyi.product.tree.DataTreeRes;

import java.util.*;

/**
 * 获取树型工具类
 * @author YangWenHui
 *
 */
public class TreeUtils {
	
	//获取顶层节点
	public static <T extends DataTreeRes<T>> List<T> getTreeList(Long topId, List<T> entityList){
		List<T> resultList = new ArrayList<>();//存储顶层的数据
		Map<Object, T> treeMap = new HashMap<>();
		T itemTree;
		for(int i=0;i<entityList.size()&&!entityList.isEmpty();i++) {
			itemTree = entityList.get(i);
			treeMap.put(itemTree.getKeyId(),itemTree);//把所有的数据放到map当中，id为key
			if(topId.equals(itemTree.getParentId()) || itemTree.getParentId() == null) {//把顶层数据放到集合中
				resultList.add(itemTree);
			
				Collections.sort(resultList);
			}
		}
		
		//循环数据，把数据放到上一级的childen属性中
		for(int i = 0; i< entityList.size()&&!entityList.isEmpty();i++) {
			itemTree = entityList.get(i);
			T data = treeMap.get(itemTree.getParentId());//在map集合中寻找父亲
			if(data != null) {//判断父亲有没有
				if(data.getChildList() == null) {
					data.setChildList(new ArrayList<>());
				}
				data.getChildList().add(itemTree);//把子节点 放到父节点childList当中
				Collections.sort(data.getChildList());
				treeMap.put(itemTree.getParentId(), data);//把放好的数据放回map当中
			}
		}
		return resultList;
	}
	
	 //对树形结构进行排序
	 public static <T extends DataTreeRes<T>> List<T> sortList(List<T> list){
		Collections.sort(list);
		for (T osr : list) {
			List<T> childList = osr.getChildList();
			if (childList != null && childList.size()>0) {
				sortList(childList);
			}
		}
		return list;
	 }
	 
	 //根据最底层的节点查询出他的所有父级节点
	 public static <T extends DataTree> List<T> getPids(List<T> resultList,T entity,List<T> osList){
		 Long pid = entity.getParentId();
		 for (T os : osList) {
			 if (pid.equals(os.getKeyId())) {
				 getPids(resultList,os,osList);
				 resultList.add(os);
			 }
		 }
		 return resultList;
	 }

	/**
	 * 通过父id，获取他下面的所有子孙id
	 * @param idList	结果集
	 * @param osList	所有的节点集合
	 * @param pid		父id
	 * @return
	 */
	public static <T extends DataTree> List<Long> getChildIds(List<Long> idList, List<T> osList, Long pid){
		for(T os: osList){
			//遍历出父id等于参数的id，add进子节点集合
			if(os.getParentId().equals(pid)){
				//递归遍历下一级
				getChildIds(idList,osList,os.getKeyId());
				idList.add(os.getKeyId());
			}
		}
		return idList;
	}
}

